package com.ving.test.mybatis01.resultset;

import com.ving.test.mybatis.binding.MapperMethod;
import com.ving.test.mybatis01.binding.MapperMethod01;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by liuweijie on 2019-11-19.
 */
public class ResultSetHandler01  {
    public <T>T handle(PreparedStatement pstmt, MapperMethod01 mapperMethod) throws Exception {
        Object resultObj = new DefaultObjectFactory().create(mapperMethod.getZlass());
        ResultSet rs = pstmt.getResultSet();
        if(rs.next()){
            int i=0;
            for (Field field : resultObj.getClass().getDeclaredFields()) {
                setValue(resultObj,field,rs,i);
            }

        }
        return (T)resultObj;
    }

    private void setValue(Object resultObj, Field field, ResultSet rs, int i) throws NoSuchMethodException, SQLException, InvocationTargetException, IllegalAccessException {

        Method setMethod = resultObj.getClass().getMethod("set" + upperCapital(field.getName()), field.getType());
        setMethod.invoke(resultObj,getResult(field,rs));
    }

    private String upperCapital(String name) {
        String first = name.substring(0,1);
        String tail = name.substring(1);
        return first.toUpperCase()+tail;
    }

    private Object getResult(Field field, ResultSet rs) throws SQLException {
        Class<?> type = field.getType();
        try {

            if (Integer.class == type) {
                return rs.getInt(field.getName());
            }
            if (String.class==type) {
                return rs.getString(field.getName());

            }
            if (Long.class==type) {
                return rs.getString(field.getName());

            }
        }catch (Exception e){

        }
        return null;
    }
}
